package cn.itcast.realm;

import cn.itcast.domain.system.Permission;
import cn.itcast.domain.system.Role;
import cn.itcast.domain.system.User;
import cn.itcast.service.PermissionService;
import cn.itcast.service.RoleService;
import cn.itcast.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

//@Service("bosRealm")
public class BosRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    @Override
    //授权 先执行认证 再执行授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("--------------------------------------------------------------------");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();//角色权限对象
            //从subject中获取user对象 为该user对象创建权限对象
        Subject subject = SecurityUtils.getSubject();
        User user= (User) subject.getPrincipal();
        //根据user查询相应的角色和权限并赋予给该user
        List<Role>roles=roleService.findByUser(user);
        for( Role role  :roles ){
            simpleAuthorizationInfo.addRole(role.getKeyword());//权限名字段为keyword
        }
        List<Permission>permissions=permissionService.findByUser(user);
        for(Permission permission : permissions){
            simpleAuthorizationInfo.addStringPermission(permission.getKeyword());
        }
        return simpleAuthorizationInfo;
    }

    @Override
    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //数据转型
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userService.findByUsername(token.getUsername());
        if (user == null) {
        /*
          用户不存在
          SimpleAuthenticationInfo
           参数1 保存在subject中的信息
           参数2 查询到的user.getpassword (null表示用户名不存在)
           参数2 realm的名称
         */
            return null;
        } else {
        /*
          用户存在
          会自动比对user.getpassword()和token.getpassword()是否匹配
          不匹配则报密码错误
         */

            return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        }

    }
}
